package ynu.edu.controller;

import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@RestController
@RequestMapping("/consumer1")
public class ConsumerController {
    @LoadBalanced
    private final RestTemplate restTemplate;

    public ConsumerController(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    // GET调用
    @GetMapping("/test-get/{id}")
    public String testGet(@PathVariable("id") String id) {
        return restTemplate.getForObject(
                "http://provider/data/{id}",
                String.class,
                id
        );
    }

    // POST调用
    @PostMapping("/test-post")
    public String testPost(@RequestBody Map<String, String> request) {
        return restTemplate.postForObject(
                "http://provider/data",
                request,
                String.class
        );
    }

    // PUT调用
    @PutMapping("/test-put/{id}")
    public String testPut(@PathVariable("id") String id, @RequestBody Map<String, String> request) {
        HttpEntity<Map<String, String>> entity = new HttpEntity<>(request);
        return restTemplate.exchange(
                "http://provider/data/{id}",
                HttpMethod.PUT,
                entity,
                String.class,
                id
        ).getBody();
    }

    // DELETE调用
    @DeleteMapping("/test-delete/{id}")
    public String testDelete(@PathVariable("id") String id) {
        restTemplate.delete("http://provider/data/{id}", id);
        return "已删除ID：" + id;
    }

}
